package sg.edu.nus.iss.team2s.jass.dao;

import java.util.*;

import sg.edu.nus.iss.team2s.jass.dto.*;
import sg.edu.nus.iss.team2s.jass.util.*;

/**
 * @author LU ZHIXIAN
 */

public class AdvertiserDAO extends AbstractPropertiesDAO {

public static final String FILENAME = "Advertiser";
	
	//get the fields, need to be overridden in the subclass
//	@Override
//	protected  String[] getFields(){
//		return new String[]{"advertiserId","fullName","address","telephone","fax","email","loginId"};
//	}
	
	@Override
	public void add(Object obj) throws DAOException {
		Advertiser advertiser=(Advertiser) obj;
		
		if (advertiser.getAdvertiserId().equalsIgnoreCase("")){
			throw new DAOException("Advertiser Id is empty");	
		}
		
		if (advertiser.getFullName().equals("") || advertiser.getEmail().equals("")){
			throw new DAOException("Either the Advertiser Name or Advertiser Email is NULL.");	
		}
		
		//check duplicate
		
		if (get(advertiser.getAdvertiserId())!=null){
			throw new DAOException("Advertiser Id is duplicated!");	
		}
		
		ArrayList<Object> arrList=(ArrayList<Object>)list();
		
		arrList.add(obj);
		
		update(arrList);
			
	}
	
	@Override
	public Object get(String key) throws DAOException {
		
		ArrayList<Object> arrList=(ArrayList<Object>)list();
		
		for(int i=0; i < arrList.size(); i++)  {
			Advertiser advertiser=(Advertiser)arrList.get(i);
		    if (advertiser.getAdvertiserId().equalsIgnoreCase(key)){
		    	return advertiser;	
		    }
			
		}
		
		throw new DAOException("NO Advertiser Record Found!");
	}

	public Advertiser getAdvertiserByLogin(String loginId) throws DAOException {
		
		ArrayList<Object> arrList=(ArrayList<Object>)list();
		
		for(int i=0; i < arrList.size(); i++)  {
			Advertiser advertiser=(Advertiser)arrList.get(i);
		    if (advertiser.getLoginId().equalsIgnoreCase(loginId)){
		    	return advertiser;	
		    }
			
		}
		
		throw new DAOException("NO Advertiser Record Found!");
	}
	
	@Override
	public List<Object> list() throws DAOException {

		List<Object> list;
		try{
			list= retrieve(AdvertiserDAO.FILENAME );	
		}
		catch(Exception exp){
			throw new DAOException(exp.getMessage(),exp.getCause());
			
		}
		return list;
	}
	@Override
	public void update(List<Object> list) throws DAOException {

		try{
			flush(list,AdvertiserDAO.FILENAME );	
		}
		catch(Exception exp){
			throw new DAOException(exp.getMessage(),exp.getCause());
			
		}
	}
	
	public void delete(Object obj) throws DAOException{
	ArrayList<Object> arrList=(ArrayList<Object>)list();
		
		for(int i=0; i < arrList.size(); i++)  {
			Advertiser advertiser=(Advertiser)arrList.get(i);
		    if (advertiser.getAdvertiserId().equalsIgnoreCase(((Advertiser)obj).getAdvertiserId())){
		    	arrList.remove(i);
		    	update(arrList);
		    	break;
		    }
			
		}
		
		throw new DAOException("NO Advertiser Record Found!");
		
	}

}
